package NewChatRoom;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

//服务器进程
public class ChatServer extends Thread{
    private int port;
    //服务器运行标记
    private boolean running =false;
    private ServerSocket ss;
    ResultToServer rs = new ResultToServer();

    public ChatServer(int port){
        this.port = port;
    }

    public void run(){
        setupServer();
    }

    public void setupServer(){
        try {
            ss = new ServerSocket(this.port);
            running = true;
            //System.out.println("服务器创建成功");
            rs.print("服务器创建成功\n");
            //循环检测要接入的客户端
            while (running){
                Socket client = ss.accept();
                //System.out.println("进入了一个客户机连接" + client.getRemoteSocketAddress());
                rs.print("进入了一个客户机连接" + client.getRemoteSocketAddress()+"\n");
                //启动处理线程
                serverHandlerThread sht = new serverHandlerThread(client);
                sht.start();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public boolean isRunning(){
        return running;
    }

    public void stopChatServer(){
        this.running = false;
        try {
            ss.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
